<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 5/18 0018
 * Time: 14:31
 */

/******************************************************** 接口通用返回部分 **************************************************/
// 获取IP地址（摘自discuz）
function getIp(){
    $ip='未知IP';
    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
        return is_ip($_SERVER['HTTP_CLIENT_IP'])?$_SERVER['HTTP_CLIENT_IP']:$ip;
    }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        return is_ip($_SERVER['HTTP_X_FORWARDED_FOR'])?$_SERVER['HTTP_X_FORWARDED_FOR']:$ip;
    }else{
        return is_ip($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:$ip;
    }
}
function is_ip($str){
    $ip=explode('.',$str);
    for($i=0;$i<count($ip);$i++){
        if($ip[$i]>255){
            return false;
        }
    }
    return preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/',$str);
}
//删除空格
function trimall($str)
{
    $qian=array(" ","　","\t","\n","\r");$hou=array("","","","","");
    return str_replace($qian,$hou,$str);
}
/**
 * @param string $data
 * 清楚数据内的null
 */
function clear_null($data){
    $data = json_decode(json_encode($data),true);
    if($data === null || $data === false){
        $data = [];
    }
    if(is_array($data) && !empty($data)){
        foreach($data as &$v){
            if($v === null || $v === false){
                $v = '';
            }else if(is_array($v)){
                clear_null($v);
            }else if(is_string($v) && stripos($v,'.') === 0){
                $v = '0'.$v;
            }
        }
    }
}
/**
 * json API 返回成功
 * @param string $msg
 * @param array $data
 * @return array
 */
function json_success($msg = '',$data = []){
    $return = [
        'code'	=> '1',
        'msg'		=> $msg,
        'data'		=> $data,
    ];
    clear_null($return['data']);
    return $return;
}

/**
 * json API 返回失败
 * @param $msg
 * @param array $data
 * @return array
 */
function json_error($msg,$data = []){
    $msg = $msg ? : '服务器错误，请稍后重试';
    $return =  [
        'code'	=> '0',
        'msg'		=> $msg,
        'data'		=> $data,
    ];
    clear_null($return['data']);
    return $return;
}

/**
 * json API 返回需要登录
 * @param $msg
 * @param array $data
 * @return array
 */
function json_login($msg = '',$data = []){
    $msg = $msg ? : '登录失效，请重新登录';
    $return =  [
        'code'	=> '2',
        'msg'		=> $msg,
        'data'		=> $data,
    ];
    clear_null($return['data']);
    return $return;
}

/**
 * json API 根据变量自动判断返回成功或失败
 * @param $var
 * @param string $error_msg
 * @param string $success_msg
 * @param array $data
 * @return array
 */
function json_return($var,$error_msg = '服务器错误，请稍后重试',$success_msg = 'OK',$data = []){
    if($var === false || $var === null){
        return json_error($error_msg,$data);
    }else{
        return json_success($success_msg,$data);
    }
}

function check_login(){

    if(!session('user')){
        return redirect('admin/login/index')
            ->withErrors('尚未登录，请先登录')
            ->withInput();
    }
}

function guid(){
    if (function_exists('com_create_guid')){
        return trim(com_create_guid(),'{}"');
    }else{
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = substr($charid, 0, 9).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,19,12);
        return $uuid;
    }
}
/**
 * 以post的形式跳转链接
 * @param $url 跳转地址
 * @param $con 参数 键值对
 */
function post_redirect($url , $con=array()){
    $args = "";
    foreach($con as $k=>$v){
        $args .= "<input type='hidden' name='{$k}' value='{$v}' />";
    }
    $session_id = session_id();
    $args .= "<input type='hidden' name='session_id' value='{$session_id}' />";
    $html = <<<EOT
<form action="{$url}" method="post" id="form">
	{$args}
	<input type="submit" value=" " style="opacity:0" />
</form>
<script>document.getElementById('form').submit();</script>
EOT;
    exit($html);
}
//对象转数组
function object_to_array($obj){
    if(is_array($obj)){
        return $obj;
    }
    $_arr = is_object($obj)? get_object_vars($obj) :$obj;
    foreach ($_arr as $key => $val){
        $val=(is_array($val)) || is_object($val) ? object_to_array($val) :$val;
        $arr[$key] = $val;
    }

    return $arr;

}
/**
 * 把对象转化为json
 */
function object_to_json($obj){
    $arr2=object_to_array($obj);//先把对象转化为数组
    return json_encode($arr2);
}